home *** CD-ROM | disk | FTP | other *** search
/ Game.EXE 2001 January / Game.EXE_01_2001.iso / demos / Blade of Darkness / data1.cab / Program_Executable_Files / Lib / PythonLib / dospath.py < prev    next >
Encoding:
Text File  |  2000-11-16  |  8.5 KB  |  343 lines

  1. # Module 'dospath' -- common operations on DOS pathnames
  2.  
  3. import os
  4. import stat
  5. import string
  6.  
  7.  
  8. # Normalize the case of a pathname.
  9. # On MS-DOS it maps the pathname to lowercase, turns slashes into
  10. # backslashes.
  11. # Other normalizations (such as optimizing '../' away) are not allowed
  12. # (this is done by normpath).
  13. # Previously, this version mapped invalid consecutive characters to a 
  14. # single '_', but this has been removed.  This functionality should 
  15. # possibly be added as a new function.
  16.  
  17. def normcase(s):
  18.     return string.lower(string.replace(s, "/", "\\"))
  19.  
  20.  
  21. # Return wheter a path is absolute.
  22. # Trivial in Posix, harder on the Mac or MS-DOS.
  23. # For DOS it is absolute if it starts with a slash or backslash (current
  24. # volume), or if a pathname after the volume letter and colon starts with
  25. # a slash or backslash.
  26.  
  27. def isabs(s):
  28.     s = splitdrive(s)[1]
  29.     return s != '' and s[:1] in '/\\'
  30.  
  31.  
  32. # Join two (or more) paths.
  33.  
  34. def join(a, *p):
  35.     path = a
  36.     for b in p:
  37.         if isabs(b):
  38.             path = b
  39.         elif path == '' or path[-1:] in '/\\':
  40.             path = path + b
  41.         else:
  42.             path = path + os.sep + b
  43.     return path
  44.  
  45.  
  46. # Split a path in a drive specification (a drive letter followed by a
  47. # colon) and the path specification.
  48. # It is always true that drivespec + pathspec == p
  49.  
  50. def splitdrive(p):
  51.     if p[1:2] == ':':
  52.         return p[0:2], p[2:]
  53.     return '', p
  54.  
  55.  
  56. # Split a path in head (everything up to the last '/') and tail (the
  57. # rest).  If the original path ends in '/' but is not the root, this
  58. # '/' is stripped.  After the trailing '/' is stripped, the invariant
  59. # join(head, tail) == p holds.
  60. # The resulting head won't end in '/' unless it is the root.
  61.  
  62. def split(p):
  63.     d, p = splitdrive(p)
  64.     slashes = ''
  65.     while p and p[-1:] in '/\\':
  66.         slashes = slashes + p[-1]
  67.         p = p[:-1]
  68.     if p == '':
  69.         p = p + slashes
  70.     head, tail = '', ''
  71.     for c in p:
  72.         tail = tail + c
  73.         if c in '/\\':
  74.             head, tail = head + tail, ''
  75.     slashes = ''
  76.     while head and head[-1:] in '/\\':
  77.         slashes = slashes + head[-1]
  78.         head = head[:-1]
  79.     if head == '':
  80.         head = head + slashes
  81.     return d + head, tail
  82.  
  83.  
  84. # Split a path in root and extension.
  85. # The extension is everything starting at the first dot in the last
  86. # pathname component; the root is everything before that.
  87. # It is always true that root + ext == p.
  88.  
  89. def splitext(p):
  90.     root, ext = '', ''
  91.     for c in p:
  92.         if c in '/\\':
  93.             root, ext = root + ext + c, ''
  94.         elif c == '.' or ext:
  95.             ext = ext + c
  96.         else:
  97.             root = root + c
  98.     return root, ext
  99.  
  100.  
  101. # Return the tail (basename) part of a path.
  102.  
  103. def basename(p):
  104.     return split(p)[1]
  105.  
  106.  
  107. # Return the head (dirname) part of a path.
  108.  
  109. def dirname(p):
  110.     return split(p)[0]
  111.  
  112.  
  113. # Return the longest prefix of all list elements.
  114.  
  115. def commonprefix(m):
  116.     if not m: return ''
  117.     prefix = m[0]
  118.     for item in m:
  119.         for i in range(len(prefix)):
  120.             if prefix[:i+1] <> item[:i+1]:
  121.                 prefix = prefix[:i]
  122.                 if i == 0: return ''
  123.                 break
  124.     return prefix
  125.  
  126.  
  127. # Is a path a symbolic link?
  128. # This will always return false on systems where posix.lstat doesn't exist.
  129.  
  130. def islink(path):
  131.     return 0
  132.  
  133.  
  134. # Does a path exist?
  135. # This is false for dangling symbolic links.
  136.  
  137. def exists(path):
  138.     try:
  139.         st = os.stat(path)
  140.     except os.error:
  141.         return 0
  142.     return 1
  143.  
  144.  
  145. # Is a path a dos directory?
  146. # This follows symbolic links, so both islink() and isdir() can be true
  147. # for the same path.
  148.  
  149. def isdir(path):
  150.     try:
  151.         st = os.stat(path)
  152.     except os.error:
  153.         return 0
  154.     return stat.S_ISDIR(st[stat.ST_MODE])
  155.  
  156.  
  157. # Is a path a regular file?
  158. # This follows symbolic links, so both islink() and isdir() can be true
  159. # for the same path.
  160.  
  161. def isfile(path):
  162.     try:
  163.         st = os.stat(path)
  164.     except os.error:
  165.         return 0
  166.     return stat.S_ISREG(st[stat.ST_MODE])
  167.  
  168.  
  169. # Are two filenames really pointing to the same file?
  170.  
  171. def samefile(f1, f2):
  172.     s1 = os.stat(f1)
  173.     s2 = os.stat(f2)
  174.     return samestat(s1, s2)
  175.  
  176.  
  177. # Are two open files really referencing the same file?
  178. # (Not necessarily the same file descriptor!)
  179. # XXX THIS IS BROKEN UNDER DOS! ST_INO seems to indicate number of reads?
  180.  
  181. def sameopenfile(fp1, fp2):
  182.     s1 = os.fstat(fp1.fileno())
  183.     s2 = os.fstat(fp2.fileno())
  184.     return samestat(s1, s2)
  185.  
  186.  
  187. # Are two stat buffers (obtained from stat, fstat or lstat)
  188. # describing the same file?
  189.  
  190. def samestat(s1, s2):
  191.     return s1[stat.ST_INO] == s2[stat.ST_INO] and \
  192.         s1[stat.ST_DEV] == s2[stat.ST_DEV]
  193.  
  194.  
  195. # Is a path a mount point?
  196. # XXX This degenerates in: 'is this the root?' on DOS
  197.  
  198. def ismount(path):
  199.     return isabs(splitdrive(path)[1])
  200.  
  201.  
  202. # Directory tree walk.
  203. # For each directory under top (including top itself, but excluding
  204. # '.' and '..'), func(arg, dirname, filenames) is called, where
  205. # dirname is the name of the directory and filenames is the list
  206. # files files (and subdirectories etc.) in the directory.
  207. # The func may modify the filenames list, to implement a filter,
  208. # or to impose a different order of visiting.
  209.  
  210. def walk(top, func, arg):
  211.     try:
  212.         names = os.listdir(top)
  213.     except os.error:
  214.         return
  215.     func(arg, top, names)
  216.     exceptions = ('.', '..')
  217.     for name in names:
  218.         if name not in exceptions:
  219.             name = join(top, name)
  220.             if isdir(name):
  221.                 walk(name, func, arg)
  222.  
  223.  
  224. # Expand paths beginning with '~' or '~user'.
  225. # '~' means $HOME; '~user' means that user's home directory.
  226. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  227. # the path is returned unchanged (leaving error reporting to whatever
  228. # function is called with the expanded path as argument).
  229. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  230. # (A function should also be defined to do full *sh-style environment
  231. # variable expansion.)
  232.  
  233. def expanduser(path):
  234.     if path[:1] <> '~':
  235.         return path
  236.     i, n = 1, len(path)
  237.     while i < n and path[i] not in '/\\':
  238.         i = i+1
  239.     if i == 1:
  240.         if not os.environ.has_key('HOME'):
  241.             return path
  242.         userhome = os.environ['HOME']
  243.     else:
  244.         return path
  245.     return userhome + path[i:]
  246.  
  247.  
  248. # Expand paths containing shell variable substitutions.
  249. # The following rules apply:
  250. #    - no expansion within single quotes
  251. #    - no escape character, except for '$$' which is translated into '$'
  252. #    - ${varname} is accepted.
  253. #    - varnames can be made out of letters, digits and the character '_'
  254. # XXX With COMMAND.COM you can use any characters in a variable name,
  255. # XXX except '^|<>='.
  256.  
  257. varchars = string.letters + string.digits + '_-'
  258.  
  259. def expandvars(path):
  260.     if '$' not in path:
  261.         return path
  262.     res = ''
  263.     index = 0
  264.     pathlen = len(path)
  265.     while index < pathlen:
  266.         c = path[index]
  267.         if c == '\'':    # no expansion within single quotes
  268.             path = path[index + 1:]
  269.             pathlen = len(path)
  270.             try:
  271.                 index = string.index(path, '\'')
  272.                 res = res + '\'' + path[:index + 1]
  273.             except string.index_error:
  274.                 res = res + path
  275.                 index = pathlen -1
  276.         elif c == '$':    # variable or '$$'
  277.             if path[index + 1:index + 2] == '$':
  278.                 res = res + c
  279.                 index = index + 1
  280.             elif path[index + 1:index + 2] == '{':
  281.                 path = path[index+2:]
  282.                 pathlen = len(path)
  283.                 try:
  284.                     index = string.index(path, '}')
  285.                     var = path[:index]
  286.                     if os.environ.has_key(var):
  287.                         res = res + os.environ[var]
  288.                 except string.index_error:
  289.                     res = res + path
  290.                     index = pathlen - 1
  291.             else:
  292.                 var = ''
  293.                 index = index + 1
  294.                 c = path[index:index + 1]
  295.                 while c != '' and c in varchars:
  296.                     var = var + c
  297.                     index = index + 1
  298.                     c = path[index:index + 1]
  299.                 if os.environ.has_key(var):
  300.                     res = res + os.environ[var]
  301.                 if c != '':
  302.                     res = res + c
  303.         else:
  304.             res = res + c
  305.         index = index + 1
  306.     return res
  307.  
  308.  
  309. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  310. # Also, components of the path are silently truncated to 8+3 notation.
  311.  
  312. def normpath(path):
  313.     path = string.replace(path, "/", "\\")
  314.     prefix, path = splitdrive(path)
  315.     while path[:1] == os.sep:
  316.         prefix = prefix + os.sep
  317.         path = path[1:]
  318.     comps = string.splitfields(path, os.sep)
  319.     i = 0
  320.     while i < len(comps):
  321.         if comps[i] == '.':
  322.             del comps[i]
  323.         elif comps[i] == '..' and i > 0 and \
  324.                       comps[i-1] not in ('', '..'):
  325.             del comps[i-1:i+1]
  326.             i = i-1
  327.         elif comps[i] == '' and i > 0 and comps[i-1] <> '':
  328.             del comps[i]
  329.         elif '.' in comps[i]:
  330.             comp = string.splitfields(comps[i], '.')
  331.             comps[i] = comp[0][:8] + '.' + comp[1][:3]
  332.             i = i+1
  333.         elif len(comps[i]) > 8:
  334.             comps[i] = comps[i][:8]
  335.             i = i+1
  336.         else:
  337.             i = i+1
  338.     # If the path is now empty, substitute '.'
  339.     if not prefix and not comps:
  340.         comps.append('.')
  341.     return prefix + string.joinfields(comps, os.sep)
  342.  
  343.